﻿// @Description: 快钱VPOS-CNP网关接口范例
// @Copyright (c) 上海快钱信息服务有限公司
// @version 1.0
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;


namespace DataTransmit
{
    #region KuaiQianHelper类，包括属性方法
    /// <summary>
    /// 信用卡消费（PUR）付款 接口逻辑实现类，公共属性和帮助方法
    /// </summary>
    public class KuaiQianHelper
    {

        #region 辅助方法
        private static bool RemoteCertificateCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    

        /// <summary>
        /// Post数据 【参数1：网关地址（例如消费：https://mas.99bill.com/cnp/purchase）2：提交的XML消费交易数据，3：商户号，4商户密码，5：商户证书地址，6：商户证书密码】
        /// </summary>
        public string HttpPost(string sUrl, string  sPostData, string sMerId, string sMerPW, string prikey_path,string prikey_password)
        {
            try
            {
                //将输入的xml内容转化为byte数组，   
                byte[] data = System.Text.Encoding.UTF8.GetBytes(sPostData);
                //byte[] data = System.Text.Encoding.UTF8.GetBytes((sPostData);

                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateCallback;

                //使用webrequest发送http消息，模拟浏览器提交的效果   
                System.Net.HttpWebRequest httpreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(new Uri(sUrl));

                //设置http的方法是post，post/get二种方法   
                httpreq.Method = "POST";
                //模拟form的类型，一般来说用这种类型的form   
                httpreq.ContentType = "application/x-www-form-urlencoded";
                //设置请求超时时间（单位：毫秒） 1分钟6000毫秒
                httpreq.Timeout = 300000;

                httpreq.AllowAutoRedirect = false;
 

                //数据长度，https要求   
                httpreq.ContentLength = data.Length;
                httpreq.Credentials = CredentialCache.DefaultCredentials;
                //获取需要的商户验证信息
                string userNamePassword = sMerId + ":" + sMerPW;
                CredentialCache mycache = new CredentialCache();
                mycache.Add(new Uri(sUrl), "Basic", new NetworkCredential(sMerId, sMerPW));
                httpreq.Credentials = mycache;
                //byte [] a=new ASCIIEncoding().GetBytes(userNamePassword);
                httpreq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(userNamePassword)));
                //加载证书
                X509Certificate2 objX509_2 = new X509Certificate2(prikey_path, prikey_password);
                httpreq.ClientCertificates.Add(objX509_2);

                //获取或设置请求的身份验证信息
                //利用二进制流发送数据   
                System.IO.Stream newStream = httpreq.GetRequestStream();

                //发送数据   
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                //得到http的返回结果   
                System.Net.HttpWebResponse res = (System.Net.HttpWebResponse)httpreq.GetResponse();

                //分析返回结果
                StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                //得到返回值
                string rtnRes = reader.ReadToEnd();
                reader.Close();

                return rtnRes;	//返回TR2数据
            }
            catch (Exception ex)
            {
                string sStr = ex.Message;
                return sStr; //返回错误
            }
        }
        //xml拼写的辅助方法
        public StringBuilder appendParam(StringBuilder reqXml, String paraName, String paraValue,  bool gen)
        {

            if (paraValue == null)
            {
                paraValue = "";
            }

            if (reqXml == null)
            {
                reqXml = new StringBuilder();
            }
            if (gen)
            {
                string str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MasMessage xmlns=\"http://www.99bill.com/mas_cnp_merchant_interface\">";
                reqXml.Append(str).Append("<").Append(paraName).Append(">").Append(paraValue).Append("</").Append(paraName).Append(">").Append("<").Append("TxnMsgContent").Append(">");
               // reqXml.Append(str).Append("<").Append(paraName).Append(">").Append(paraValue).Append("</").Append(paraName).Append(">").Append("<").Append(Content).Append(">");
           }
            
            if ((!(paraName.Equals(""))) && (!(paraValue.Equals(""))))
            {
                reqXml.Append("<").Append(paraName).Append(">").Append(paraValue).Append("</").Append(paraName).Append(">");
            }

            else if ((paraName.Equals("")) && paraValue.Equals(""))
            {

                reqXml.Append("</").Append("TxnMsgContent").Append(">").Append("</MasMessage>");
            }
            return reqXml;
        }

        //xml拼写的辅助方法
        public  StringBuilder appendParam(StringBuilder reqXml, String paraName, String paraValue)
        {

            if (paraValue == null){
            
                paraValue = "";
            }

            if (reqXml == null)
            {
                reqXml = new StringBuilder();
                string str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MasMessage xmlns=\"http://www.99bill.com/mas_cnp_merchant_interface\">";
                reqXml.Append(str).Append("<").Append(paraName).Append(">").Append(paraValue).Append("</").Append(paraName).Append(">").Append("<").Append("TxnMsgContent").Append(">");
            }
            else if ((!(paraName.Equals(""))) && (!(paraValue.Equals(""))))
            {
                reqXml.Append("<").Append(paraName).Append(">").Append(paraValue).Append("</").Append(paraName).Append(">");
            }

            else if ((paraName.Equals("")) && paraValue.Equals(""))
            {

                reqXml.Append("</").Append("TxnMsgContent").Append(">").Append("</MasMessage>");
            }
            return reqXml;
        }
        
        #endregion

    }
    #endregion

}
